package org.hiucung.hlsdownloader.ui.components

import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.viewinterop.AndroidView
import org.hiucung.hlsdownloader.view.ComposeGSYVideoPlayer

/**
 * @title: GSYVideoPlayer
 * @projectName HLS Downloader
 * @description:
 * @author Kicc
 * @date 2025/9/4 0:13
 */
@Composable
fun GSYVideoPlayer(
    modifier: Modifier = Modifier,
    videoUrl: String,
    videoTitle: String = "",
    isPlaying: Boolean = true, // 外部控制播放/暂停的状态
    onBackPressed: (() -> Unit)? = null // 处理全屏时的返回键
) {

    AndroidView(
        modifier = modifier,
        factory = { ctx ->
            // 创建 View 实例
            ComposeGSYVideoPlayer(context = ctx).apply {
                setVideoData(videoUrl, videoTitle)
                setBackFromFullScreenListener {
                    release()
                    onBackPressed?.invoke()
                }
                isAutoFullWithSize = true
                setNeedAutoAdaptation(true)
            }
        },
        update = { player ->
            // 当外部状态变化时更新 View
            if (isPlaying) {
                player.startPlayLogic() // 开始播放
            } else {
                player.onVideoPause() // 暂停播放
            }
            // 如果 URL 或标题发生变化，也在这里更新
            if (player.videoUrl != videoUrl || player.videoTitle != videoTitle) {
                player.setVideoData(videoUrl, videoTitle)
            }
        }
    )
}